package com.iwhalecloud.bss.kite.cucc.service.batch;

import java.io.IOException;
import java.io.InputStream;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.google.common.collect.Lists;
import com.iwhalecloud.bss.kite.cart.client.api.cart.query.IQueryKiteShoppingCartService;
import com.iwhalecloud.bss.kite.client.api.scene.operate.IOperateSceneOfferInstService;
import com.iwhalecloud.bss.kite.client.api.scene.operate.IOperateSceneProdInstService;
import com.iwhalecloud.bss.kite.client.dto.spec.in.ContractOfferDetailDTO;
import com.iwhalecloud.bss.kite.common.constant.ErrorConsts;
import com.iwhalecloud.bss.kite.common.constant.KeyConsts;
import com.iwhalecloud.bss.kite.common.executor.MultiThreaExecutorManager;
import com.iwhalecloud.bss.kite.common.executor.enums.ExecutorTypeEmun;
import com.iwhalecloud.bss.kite.common.executor.task.ExecuteTask;
import com.iwhalecloud.bss.kite.common.util.FunctionWrapper;
import com.iwhalecloud.bss.kite.common.util.KiteBeanUtils;
import com.iwhalecloud.bss.kite.common.util.KiteDateUtils;
import com.iwhalecloud.bss.kite.common.util.KiteListUtils;
import com.iwhalecloud.bss.kite.common.util.KiteMapUtils;
import com.iwhalecloud.bss.kite.common.util.KiteObjectUtils;
import com.iwhalecloud.bss.kite.common.util.KiteStringUtils;
import com.iwhalecloud.bss.kite.common.util.SeqUtils;
import com.iwhalecloud.bss.kite.cucc.client.api.attr.IUnicomRegionService;
import com.iwhalecloud.bss.kite.cucc.client.api.batch.IBatchAcceptService;
import com.iwhalecloud.bss.kite.cucc.client.api.batch.IBatchConfigService;
import com.iwhalecloud.bss.kite.cucc.client.api.scene.ICuccSceneService;
import com.iwhalecloud.bss.kite.cucc.client.api.shoppingcart.operate.ICuccOperateShoppingCartService;
import com.iwhalecloud.bss.kite.cucc.client.dto.attr.UnicomRegion;
import com.iwhalecloud.bss.kite.cucc.client.dto.attr.UnicomRegionQry;
import com.iwhalecloud.bss.kite.cucc.client.dto.batch.KiteBatchAccept;
import com.iwhalecloud.bss.kite.cucc.client.dto.batch.KiteBatchAcceptDetail;
import com.iwhalecloud.bss.kite.cucc.client.dto.batch.KiteBatchConfig;
import com.iwhalecloud.bss.kite.cucc.client.dto.collect.CollectImportDTO;
import com.iwhalecloud.bss.kite.cucc.client.dto.collect.CreateCollectImportDTO;
import com.iwhalecloud.bss.kite.cucc.client.vo.batch.BatchAccepImportFileVO;
import com.iwhalecloud.bss.kite.cucc.client.vo.scene.BusimportDetailVO;
import com.iwhalecloud.bss.kite.cucc.common.constant.CuccServiceOfferConsts;
import com.iwhalecloud.bss.kite.cucc.common.constant.LocalDcPublicConsts;
import com.iwhalecloud.bss.kite.cucc.common.constant.LocalKeyConsts;
import com.iwhalecloud.bss.kite.cucc.common.constant.LocalServiceOfferConsts;
import com.iwhalecloud.bss.kite.cucc.common.util.KiteAssert;
import com.iwhalecloud.bss.kite.cucc.dataservice.mapper.batch.KiteBatchAcceptDetailMapper;
import com.iwhalecloud.bss.kite.cucc.dataservice.mapper.batch.KiteBatchAcceptMapper;
import com.iwhalecloud.bss.kite.cucc.service.batch.enums.BatchAcceptStatusEnum;
import com.iwhalecloud.bss.kite.cucc.service.batch.task.InputCheckDataTask;
import com.iwhalecloud.bss.kite.cucc.service.util.ExcelUtil;
import com.iwhalecloud.bss.kite.dataservice.cache.AttrValueCache;
import com.iwhalecloud.bss.kite.dataservice.cache.DcPublicCache;
import com.iwhalecloud.bss.kite.dataservice.cache.DcSystemParamCache;
import com.iwhalecloud.bss.kite.dataservice.cache.OfferCache;
import com.iwhalecloud.bss.kite.manager.api.IOperateSceneInstService;
import com.iwhalecloud.bss.kite.manager.api.IQuerySceneInstService;
import com.iwhalecloud.bss.kite.manager.dto.KiteAttrDTO;
import com.iwhalecloud.bss.kite.manager.enums.ActionType;
import com.iwhalecloud.bss.kite.manager.enums.InstType;
import com.iwhalecloud.bss.kite.manager.inst.KiteAttr;
import com.iwhalecloud.bss.kite.manager.inst.KiteInst;
import com.iwhalecloud.bss.kite.manager.inst.KiteOfferInst;
import com.iwhalecloud.bss.kite.manager.inst.KiteOfferInstContract;
import com.iwhalecloud.bss.kite.manager.inst.KiteOfferInstDiscount;
import com.iwhalecloud.bss.kite.manager.inst.KiteProdInst;
import com.iwhalecloud.bss.kite.manager.inst.KiteSceneInst;
import com.ztesoft.bss.common.bo.LoginInfo;
import com.ztesoft.bss.common.bo.StaffInfo;
import com.ztesoft.bss.common.bo.UserInfo;
import com.ztesoft.bss.common.exception.BssException;
import com.ztesoft.bss.common.util.ContextUtil;
import com.ztesoft.bss.common.util.I18nUtil;
import com.ztesoft.bss.common.util.SpringUtil;

import lombok.RequiredArgsConstructor;
import tk.mybatis.mapper.entity.Example;

/**
 * @author : xie.zhengjun
 */
@Service
@RequiredArgsConstructor
public class BatchAcceptService implements IBatchAcceptService {
    private final IQuerySceneInstService querySceneInstService;

    private final IOperateSceneInstService operateSceneInstService;

    private final ICuccOperateShoppingCartService operateShoppingCartService;

    private final KiteBatchAcceptMapper kiteBatchAcceptMapper;

    private final KiteBatchAcceptDetailMapper kiteBatchAcceptDetailMapper;

    private final IBatchConfigService localBatchAcceptService;

    private final LocalBatchAcceptBO localBatchAcceptBO;

    @Autowired
    private IOperateSceneOfferInstService operateSceneOfferInstService;

    @Autowired
    private IOperateSceneProdInstService operateSceneProdInstService;

    @Override
    public String importData(InputStream inputStream, boolean isXls, String sceneInstId, String fileName,
                             String importType) {
        // 处理excel
        StringBuilder result = new StringBuilder();
        List<Object> list = new ArrayList<>();
        try {
            List<List<String>> datas = ExcelUtil.getExcelData(inputStream, 0, isXls);
            if (KiteListUtils.isEmpty(datas) || datas.size() <= 1) {
                BssException.throwOut("", "", "导入的数据为空，请检查");
            }
            if (KiteStringUtils.isEmpty(importType)) {
                importType = querySceneInstService.getCommonAttrValue(sceneInstId, "importType");
            }
            if (KiteStringUtils.isEmpty(importType)) {
                BssException.throwOut("", "", "导入类型未选择，请检查");
            }
            String limitNum = DcPublicCache.getCodea(LocalDcPublicConsts.BATCH_IMPORT_NUM_LIMIT, importType);
            if (KiteStringUtils.isNotEmpty(limitNum) && datas.size() > Integer.parseInt(limitNum)) {
                BssException.throwOut("", "", "导入数据不能超过限制的数量，限制为：" + limitNum);
            }

            KiteSceneInst sceneInst = querySceneInstService.getSceneInst(sceneInstId);
            int dataNum = datas.size() - 1;
            if (KiteStringUtils.equals(LocalKeyConsts.COLLECTION_GROUP_IMPORT_TYPE_1000, importType)) {
                datas.stream().skip(1).forEach(data -> {
                    List<KiteAttr> kiteAttrs = genAttrs4Type1000(data);
                    list.add(kiteAttrs);

                });
            }
            else if (KiteStringUtils.equals(LocalKeyConsts.COLLECTION_GROUP_IMPORT_TYPE_2000, importType)) {
                sceneInst.setServiceOfferId(LocalServiceOfferConsts.SERVICE_OFFER_COLLECTION_GROUP_ADD);
                sceneInst.setOperType(LocalServiceOfferConsts.SERVICE_OFFER_COLLECTION_GROUP_ADD);
                datas.stream().skip(1).forEach(data -> {
                    List<KiteAttr> kiteAttrs = genAttrs4Type2000(data);
                    if (kiteAttrs != null) {
                        list.add(kiteAttrs);
                    }
                });
            }
            else if (KiteStringUtils.equals(LocalKeyConsts.COLLECTION_GROUP_IMPORT_TYPE_3000, importType)) {
                sceneInst.setServiceOfferId(LocalServiceOfferConsts.SERVICE_OFFER_COLLECTION_GROUP_DEL);
                sceneInst.setOperType(LocalServiceOfferConsts.SERVICE_OFFER_COLLECTION_GROUP_DEL);
                datas.stream().skip(1).forEach(data -> {
                    List<KiteAttr> kiteAttrs = genAttrs4Type3000(data);
                    if (kiteAttrs != null) {
                        list.add(kiteAttrs);
                    }
                });
            }
            else {
                list.addAll(datas);
                KiteOfferInst offerInst = querySceneInstService.getOfferInst(sceneInst.getCustId(), sceneInst.getRootInstId());
                if (BatchAcceptUtil.isTwoTitile(offerInst.getAttrValue("cateId"))) {
                    dataNum--;
                }
            }
            operateSceneInstService.createSceneInst(sceneInst);
            this.operateSceneInstService.putExtParameter(sceneInstId, "importDataList", list);
            this.operateSceneInstService.putExtParameter(sceneInstId, "importFileName", fileName);
            this.operateSceneInstService
                .putExtParameter(sceneInstId, "importRowsNum", KiteStringUtils.valueOf(dataNum));
            this.operateSceneInstService.putExtParameter(sceneInstId, "importType", importType);

            result.append("共导入").append(dataNum).append("条，成功").append(dataNum);
        }
        catch (IOException e) {
            ErrorConsts.BUSI_COMMON_ERROR.throwOut(e, I18nUtil.getMessage("BSS_KITE_BATCH_000046"));
        }
        return result.toString();
    }

    private List<KiteAttr> genAttrs4Type3000(List<String> data) {
        List<KiteAttr> kiteAttrs = new ArrayList<>();
        CollectImportDTO collectImportDTO = new CollectImportDTO(data.size() > 0 ? data.get(0) : "",
            data.size() > 1 ? data.get(1) : "", "");
        // 都为空直接返回null
        if (KiteStringUtils.isEmpty(collectImportDTO.getGroupSerialNumber()) && KiteStringUtils.isEmpty(collectImportDTO.getSerialNumber())
            && KiteStringUtils.isEmpty(collectImportDTO.getTelecomType())) {
            return null;
        }
        KiteAttr groupSerialNumberAttr = new KiteAttr();
        groupSerialNumberAttr.setFieldName("groupSerialNumber");
        groupSerialNumberAttr.setValue(collectImportDTO.getGroupSerialNumber());
        groupSerialNumberAttr.setCname("收入归集集团业务号码");
        KiteAttr serialNumberAttr = new KiteAttr();
        serialNumberAttr.setFieldName("serialNumber");
        serialNumberAttr.setValue(collectImportDTO.getSerialNumber());
        serialNumberAttr.setCname("用户号码");
        kiteAttrs.add(groupSerialNumberAttr);
        kiteAttrs.add(serialNumberAttr);
        return kiteAttrs;
    }

    private List<KiteAttr> genAttrs4Type2000(List<String> data) {
        List<KiteAttr> kiteAttrs = new ArrayList<>();
        String telecomType = AttrValueCache
            .getAttrValueByAttrValueName("20210304001", data.size() > 2 ? data.get(2) : "");
        CollectImportDTO collectImportDTO = new CollectImportDTO(data.size() > 0 ? data.get(0) : "",
            data.size() > 1 ? data.get(1) : "", telecomType);
        // 都为空直接返回null
        if (KiteStringUtils.isEmpty(collectImportDTO.getGroupSerialNumber()) && KiteStringUtils.isEmpty(collectImportDTO.getSerialNumber())
            && KiteStringUtils.isEmpty(collectImportDTO.getTelecomType())) {
            return null;
        }
        KiteAttr groupSerialNumberAttr = new KiteAttr();
        groupSerialNumberAttr.setFieldName("groupSerialNumber");
        groupSerialNumberAttr.setValue(collectImportDTO.getGroupSerialNumber());
        groupSerialNumberAttr.setCname("收入归集集团业务号码");
        KiteAttr serialNumberAttr = new KiteAttr();
        serialNumberAttr.setFieldName("serialNumber");
        serialNumberAttr.setValue(collectImportDTO.getSerialNumber());
        serialNumberAttr.setCname("用户号码");
        KiteAttr telecomTypeAttr = new KiteAttr();
        telecomTypeAttr.setFieldName("telecomType");
        telecomTypeAttr.setValue(collectImportDTO.getTelecomType());
        telecomTypeAttr.setCname("电信类型");
        kiteAttrs.add(groupSerialNumberAttr);
        kiteAttrs.add(serialNumberAttr);
        kiteAttrs.add(telecomTypeAttr);
        return kiteAttrs;
    }

    private List<KiteAttr> genAttrs4Type1000(List<String> data) {
        List<KiteAttr> kiteAttrs = new ArrayList<>();
        CreateCollectImportDTO createCollectImportDTO = new CreateCollectImportDTO(data.size() > 0 ? data.get(0) : "",
            data.size() > 1 ? data.get(1) : "", data.size() > 2 ? data.get(2) : "", data.size() > 3 ? data.get(3) : "");
        KiteAttr groupIdAttr = new KiteAttr();
        groupIdAttr.setFieldName("groupId");
        groupIdAttr.setValue(createCollectImportDTO.getGroupId());
        groupIdAttr.setCname("集团客户编号");
        KiteAttr groupNameAttr = new KiteAttr();
        groupNameAttr.setFieldName("groupName");
        groupNameAttr.setValue(createCollectImportDTO.getGroupName());
        groupNameAttr.setCname("收入归集集团名称");
        KiteAttr contractCodeAttr = new KiteAttr();
        contractCodeAttr.setFieldName("contractCode");
        contractCodeAttr.setValue(createCollectImportDTO.getContractCode());
        contractCodeAttr.setCname("合同编号");
        KiteAttr accountIdAttr = new KiteAttr();
        accountIdAttr.setFieldName("accountId");
        accountIdAttr.setValue(createCollectImportDTO.getAccountId());
        accountIdAttr.setCname("账户标识");
        kiteAttrs.add(groupIdAttr);
        kiteAttrs.add(groupNameAttr);
        kiteAttrs.add(contractCodeAttr);
        kiteAttrs.add(accountIdAttr);
        return kiteAttrs;
    }

    @Override
    public String saveImport(String sceneInstId, String custId) {
        Map<String, Object> extParameter = querySceneInstService.getExtParameter(sceneInstId);
        List<?> dataList = (List<?>) extParameter.get("importDataList");
        String fileName = (String) extParameter.get("importFileName");
        String importType = (String) extParameter.get("importType");
        String rowsNum = (String) extParameter.get("importRowsNum");
        if (KiteListUtils.isEmpty(dataList)) {
            BssException.throwOut("", "", "导入的数据为空，请检查");
        }
        CompletableFuture.runAsync(FunctionWrapper.wrapLoginInfoAndTrans(
            (Runnable) () -> this.operateShoppingCartService
                .toSettle(ContextUtil.getSimpleLoginInfo(), sceneInstId, null,
                    ContextUtil.getSimpleLoginInfo().getUserId().toString(), custId,
                    KeyConsts.SHOPPING_CART_GROUP_STATUS_SETTLE)));
        // TODO: 判断是否提交成功
        Long batchId = insertBatchAccept(sceneInstId, dataList, fileName, importType, rowsNum);

        return "订单提交成功，批次号：" + batchId + "，可稍后在导入结果查询功能查询处理结果。";
    }

    @Override
    public Long insertBatchAccept(String sceneInstId, List<?> dataList, String fileName, String importType, String rowsNum) {
        // 写批量业务受理文件表
        Long batchId = Long.valueOf(SeqUtils.getNext("SEQ_KITE_BATCH_ACCEPT_BATCH_ID"));
        insertKiteBatchAccept(sceneInstId, fileName, rowsNum, importType, null, batchId);
        // 写批量业务受理明细表
        insertKiteBatchAcceptDetail(batchId, dataList);
        return batchId;
    }

    private List<KiteBatchAcceptDetail> insertKiteBatchAcceptDetail(Long batchId, List<?> dataList) {
        List<KiteBatchAcceptDetail> kiteBatchAcceptDetails = new ArrayList<>();
        LocalDateTime now = LocalDateTime.now();
        List<String> checkList = Lists.newArrayList();
        for (int i = 0; i < dataList.size(); i++) {
            Object o = dataList.get(i);

            KiteBatchAcceptDetail kiteBatchAcceptDetail = new KiteBatchAcceptDetail()
                .setDetailId(Long.valueOf(SeqUtils.getNext("SEQ_KITE_BATCH_ACCEPT_DETAIL_DETAIL_ID")))
                .setBatchId(batchId).setLineNum(i + 2).setAttrJson(JSON.toJSONString(o)).setOfferInstId(null)
                .setExtOrderId("").setCheckStatus("1000").setCheckResult("").setStatusCd("1000").setStatusDate(now)
                .setDealResult("");
            if (checkList.contains(JSON.toJSONString(o))) {
                kiteBatchAcceptDetail.setCheckStatus("1100").setCheckResult("校验失败：导入数据重复，请检查");
            }
            checkList.add(JSON.toJSONString(o));
            kiteBatchAcceptDetails.add(kiteBatchAcceptDetail);
        }
        if (KiteListUtils.isNotEmpty(kiteBatchAcceptDetails)) {
            kiteBatchAcceptDetailMapper.insertBatch(kiteBatchAcceptDetails);
        }

        return kiteBatchAcceptDetails;
    }

    private void updateKiteBatchAcceptDetail(List<KiteBatchAcceptDetail> dataList) {
        kiteBatchAcceptDetailMapper.updateBatchByPrimaryKeySelective(dataList);
    }

    @Override
    public void insertKiteBatchAccept(String sceneInstId, String fileName, String importNum, String importType,
                                       String cartId, Long batchId) {
        KiteSceneInst kiteSceneInst = querySceneInstService.getSceneInst(sceneInstId);
        String rootInstId = kiteSceneInst.getRootInstId();
        InstType rootInstType = kiteSceneInst.getRootInstType();
        String serviceOfferId = kiteSceneInst.getServiceOfferId();
        String custId = kiteSceneInst.getCustId();
        LocalDateTime now = LocalDateTime.now();
        LoginInfo loginInfo = ContextUtil.getLoginInfo();
        UserInfo userInfo = loginInfo.getUserInfo();
        Map<String, Object> extParams = userInfo.getExtParams();
        StaffInfo staffInfo = loginInfo.getStaffInfo();
        if (KiteStringUtils.isEmpty(cartId)) {
            cartId = Optional.ofNullable(kiteSceneInst.getCartId())
                .orElse(SpringUtil.getBean(ICuccSceneService.class).getCartIdFromES().getResultObject());
        }

        KiteInst kiteInst = this.querySceneInstService.getKiteInst(custId, rootInstType, rootInstId);

        KiteBatchAccept kiteBatchAccept = new KiteBatchAccept();
        kiteBatchAccept.setBatchId(batchId)
            .setFileName(fileName).setImportType(importType).setImportNum(Long.valueOf(importNum))
            .setServiceOfferId(serviceOfferId).setSceneInstId(Long.valueOf(sceneInstId)).setCreateDate(now)
            .setOfferId(Optional.ofNullable(kiteInst).map(KiteInst::getSpecId).orElse(""))
            .setOfferName(Optional.ofNullable(kiteInst).map(KiteInst::getSpecName).orElse(""))
            .setCreateStaff(staffInfo.getStaffId()).setCreateStaffCode(staffInfo.getStaffCode())
            .setCreateOrgId(loginInfo.getOrgInfo().getOrgId().toString()).setProvinceId(userInfo.getPostProvinceNbr())
            .setLanId(ContextUtil.getLandId()).setRegionId(Long.toString(userInfo.getPostRegionId()))
            .setCartId(Long.valueOf(cartId)).setJkStaffId(KiteMapUtils.getString(extParams, "accountId"))
            .setJkStaffCode(KiteMapUtils.getString(extParams, "account"))
            .setStatusCd(BatchAcceptStatusEnum.STATUS_CD_1000.getStatusCd()).setStatusDate(now).setStatusDesc("")
            .setCustId(Long.valueOf(custId)).setCreateOrgName(loginInfo.getOrgInfo().getOrgName());
        kiteBatchAcceptMapper.insert(kiteBatchAccept);
    }

    @Override
    public String importBatchAcceptData(InputStream inputStream, boolean isXls, String sceneInstId, String fileName,
                                        String importType, Long batchId) {
        String existBatchId = this.querySceneInstService.getExtParameterValue(sceneInstId, "batchId");
        if (KiteStringUtils.isNotEmpty(existBatchId)) {
            ErrorConsts.BUSI_COMMON_ERROR.throwOut("已存在导入业务文件，如需重新导入，请先删除");
        }

        KiteSceneInst sceneInst = querySceneInstService.getSceneInst(sceneInstId);
        if (KiteStringUtils
            .equals(sceneInst.getServiceOfferId(), CuccServiceOfferConsts.SERVICE_OFFER_RESOURCE_CHECK)) {
            importType = LocalKeyConsts.BATCH_ACCEPT_IMPORT_TYPE_5000;
        }

        // 处理导入数据A
        importData(inputStream, isXls, sceneInstId, fileName, importType);

        KiteOfferInst offerInst = querySceneInstService.getOfferInst(sceneInst.getCustId(), sceneInst.getRootInstId());
        int titileNum = BatchAcceptUtil.isTwoTitile(offerInst.getAttrValue("cateId")) ? 2 : 1;
        List<List<Object>> dataList = querySceneInstService.getExtParameterValue(sceneInstId, "importDataList");

        // 标题占2行时，第二行读取值会出现两种情况，""或null，当第二行所有列都为null时，会被下面【去空】逻辑删除，导致后续数据不对
        if(titileNum == 2 || KiteStringUtils.equalsAny(sceneInst.getServiceOfferId(), LocalServiceOfferConsts.SERVICE_OFFER_COP_MEMBER_JOIN,
            LocalServiceOfferConsts.SERVICE_OFFER_COP_MEMBER_QUIT)) {
            if(dataList.size() > 1) {
                // 前两行标题行特殊处理，为null的置""，防止被删除
                for (int i = 0; i < 2; i++) {
                    if(KiteListUtils.isNotEmpty(dataList.get(i)) && dataList.get(i).stream().allMatch(Objects::isNull)) {
                        dataList.get(i).set(0, "");
                    }
                }
            }
        }

        // 去空
        dataList.removeIf(data -> KiteListUtils.isEmpty(data) || data.stream().allMatch(Objects::isNull));
        this.operateSceneInstService.putExtParameter(sceneInstId, "importDataList", dataList);

        String importRowsNum = querySceneInstService.getExtParameterValue(sceneInstId, "importRowsNum");
        String spu = offerInst.getAttrValue("saleGoodsCode");
        if (KiteStringUtils.isEmpty(spu)) {
            spu = querySceneInstService.getExtParameterValue(sceneInstId, "saleGoodsCode");
        }
        KiteAssert.notBlank(spu, ErrorConsts.BUSI_COMMON_ERROR, "商品spu不能为空");
        // 数量校验
        List<Map<String, Object>> tmpAttrList = checkNumber(dataList, offerInst.getAttrValue("cateId"), spu,
            sceneInstId, fileName);
        String cartId = sceneInst.getCartId();
        if (KiteStringUtils.isEmpty(cartId)) {
            IQueryKiteShoppingCartService queryKiteShoppingCartService = SpringUtil
                .getBean(IQueryKiteShoppingCartService.class);
            // 获取分片键 cartId
            cartId = queryKiteShoppingCartService
                .getShoppingCartIdByEs(ContextUtil.getSimpleLoginInfo().getUserId().toString()).getResultObject()
                .toString();
        }
        // 写表
        if (batchId == null) {
            batchId = Long.valueOf(SeqUtils.getNext("SEQ_KITE_BATCH_ACCEPT_BATCH_ID"));
        }
        insertKiteBatchAccept(sceneInstId, fileName, importRowsNum, importType, cartId, batchId);
        // 转换attrJson
        List<List<KiteAttr>> attrList = new ArrayList<>();
        dealAttrList(dataList, tmpAttrList, attrList, sceneInst.getServiceOfferId(), titileNum);
        List<KiteBatchAcceptDetail> kiteBatchAcceptDetails = insertKiteBatchAcceptDetail(batchId, attrList);
        this.operateSceneInstService.putExtParameter(sceneInstId, "batchId", batchId.toString());

        if (!KiteStringUtils.equalsAny(sceneInst.getServiceOfferId(), LocalServiceOfferConsts.SERVICE_OFFER_COP_MEMBER_JOIN,
            LocalServiceOfferConsts.SERVICE_OFFER_COP_MEMBER_QUIT)) {
            // 将第一条数据填入场景实例节点中
            List<KiteAttr> kiteAttrs = attrList.get(0);
            localBatchAcceptBO
                .setProdAttr(sceneInstId, kiteAttrs, sceneInst.getCustId(), sceneInst.getRootInstId(), null);
//            localBatchAcceptBO.setProdAttrUserInfo(sceneInstId, sceneInst.getCustId(), sceneInst.getRootInstId(), null);
            Example example = new Example(KiteBatchAcceptDetail.class);
            example.createCriteria().andEqualTo("detailId", kiteBatchAcceptDetails.get(0).getDetailId())
                .andEqualTo("batchId", kiteBatchAcceptDetails.get(0).getBatchId());
            kiteBatchAcceptDetailMapper.updateByExampleSelective(
                new KiteBatchAcceptDetail().setOfferInstId(Long.valueOf(sceneInst.getRootInstId())), example);
        }
        return batchId.toString();
    }

    private void dealAttrList(List<List<Object>> dataList, List<Map<String, Object>> tmpAttrList,
                              List<List<KiteAttr>> attrList, String serviceOfferId, int titileNum) {
        if (KiteStringUtils.equalsAny(serviceOfferId, LocalServiceOfferConsts.SERVICE_OFFER_COP_MEMBER_JOIN,
            LocalServiceOfferConsts.SERVICE_OFFER_COP_MEMBER_QUIT)) {
            dataList.stream().skip(2).forEach(data -> {
                List<KiteAttr> attrList1 = new ArrayList<>();
                for (int i = 0; i < data.size(); i++) {
                    KiteAttr attr = new KiteAttr();
                    String value = (String) data.get(i);
                    if (KiteStringUtils.equals(value, "加入")) {
                        attr.setValue(LocalServiceOfferConsts.SERVICE_OFFER_COP_MEMBER_JOIN);
                        attr.setFieldName("operType");
                        attr.setCname("操作");
                    }
                    else if (KiteStringUtils.equals(value, "退出")) {
                        attr.setValue(LocalServiceOfferConsts.SERVICE_OFFER_COP_MEMBER_QUIT);
                        attr.setFieldName("operType");
                        attr.setCname("操作");
                    }
                    else {
                        attr.setValue(value);
                        attr.setFieldName("serialNumber");
                        attr.setCname("号码");
                    }
                    attrList1.add(attr);
                }
                attrList.add(attrList1);
            });
        }
        else {
            dataList.stream().skip(titileNum).forEach(data -> {
                List<KiteAttr> attrList1 = new ArrayList<>();
                for (int i = 0; i < data.size(); i++) {
                    if (i >= tmpAttrList.size()) {
                        break;
                    }
                    KiteAttr attr = new KiteAttr();
                    String value = (String) data.get(i);
                    attr.setValue(value);
                    Map<String, Object> tmpAttr = tmpAttrList.get(i);
                    String fieldName = KiteMapUtils.getString(tmpAttr, "fieldName");
                    attr.setFieldName(fieldName);
                    String cname = KiteMapUtils.getString(tmpAttr, "cname");
                    cname = cname.trim().replace("*", "");
                    attr.setCname(cname);
                    attrList1.add(attr);
                }
                attrList.add(attrList1);
            });
        }
    }

    @Override
    public String updateBatchAcceptData(InputStream inputStream, boolean isXls, String sceneInstId, String fileName,
        String importType) {
        // 取校验失败的数据
        String batchId = querySceneInstService.getExtParameterValue(sceneInstId, "batchId");
        List<KiteBatchAcceptDetail> failDetails = this.listCheckFailDetail(batchId);
        if (KiteListUtils.isEmpty(failDetails)) {
            BssException.throwOut("", "", "没有需要更新的校验失败记录");
        }
        // List<Integer> failLineNums = failDetails.stream().map(KiteBatchAcceptDetail::getLineNum)
        // .collect(Collectors.toList());
        // 处理导入数据A
        importData(inputStream, isXls, sceneInstId, fileName, importType);

        KiteSceneInst sceneInst = querySceneInstService.getSceneInst(sceneInstId);
        KiteInst offerInst = querySceneInstService.getKiteInst(sceneInst.getCustId(), sceneInst.getRootInstType(),
            sceneInst.getRootInstId());
        List<List<Object>> dataList = querySceneInstService.getExtParameterValue(sceneInstId, "importDataList");

        // 获取新导入的数据
        // List<List<Object>> updateDataList = Lists.newArrayList();
        // failLineNums.forEach(lineNum -> {
        // lineNum = lineNum - 2;
        // updateDataList.add(dataList.get(lineNum));
        // });

        // 数量校验
        List<Map<String, Object>> tmpAttrList = checkNumber(dataList, offerInst.getAttrValue("cateId"), offerInst.getAttrValue("saleGoodsCode"), sceneInstId,
            fileName);
        // 转换attrJson
        List<List<KiteAttr>> attrList = new ArrayList<>();
        dealAttrList(dataList, tmpAttrList, attrList, sceneInst.getServiceOfferId(), 2);
        // 设置新数据
        failDetails.forEach(failDetail -> {
            failDetail.setCheckStatus("1000");
            failDetail.setCheckResult(null);
            failDetail.setAttrJson(JSONObject.toJSONString(attrList.get(failDetail.getLineNum() - 2)));
        });

        // 更新数据
        // updateKiteBatchAcceptDetail(failDetails);
        List<String> failDetailIds =
            failDetails.stream().map(failDetail -> failDetail.getDetailId().toString()).collect(Collectors.toList());
        kiteBatchAcceptDetailMapper.deleteDetailByBatchId(failDetailIds, batchId);
        kiteBatchAcceptDetailMapper.insertBatch(failDetails);
        return batchId;
    }

    @Override
    public String converBatchAcceptData(InputStream inputStream, boolean isXls, String sceneInstId, String fileName,
                                        String importType) {
        String batchId = this.querySceneInstService.getExtParameterValue(sceneInstId, "batchId");
        this.deleteData(batchId);
        this.operateSceneInstService.removeExtParameter(sceneInstId, "batchId");
        return this.importBatchAcceptData(inputStream, isXls, sceneInstId, fileName, importType, Long.parseLong(batchId));
    }

    private List<Map<String, Object>> checkNumber(List<List<Object>> dataList, String cateId, String offerId,
                                                  String sceneInstId, String fileName) {
        KiteSceneInst kiteSceneInst = this.querySceneInstService.getSceneInst(sceneInstId);
        String serviceOfferId = Objects.nonNull(kiteSceneInst) ? kiteSceneInst.getServiceOfferId() : "";
        if (KiteStringUtils.equalsAny(serviceOfferId, LocalServiceOfferConsts.SERVICE_OFFER_COP_MEMBER_JOIN,
            LocalServiceOfferConsts.SERVICE_OFFER_COP_MEMBER_QUIT)) {
            // 最多200条、最少1
            if (KiteListUtils.isEmpty(dataList) || dataList.size() <= 1 || dataList.size() - 2 > 300) {
                BssException.throwOut("", "", "批量上传支持最多300条、最少1条信息");
            }
            return new ArrayList<>();
        }

        String num = DcSystemParamCache.getDcParamVal("BATCH_ACCEPT_IMPORT_NUM");
        if (KiteStringUtils.isEmpty(num)) {
            num = "200";
        }
        // 最多200条、最少1
        if (KiteListUtils.isEmpty(dataList) || dataList.size() <= 1 || dataList.size() - 2 > Integer.parseInt(num)) {
            BssException.throwOut("", "", "批量上传支持最多" + num + "条、最少1条信息");
        }
        String applyRegionCode = Objects.nonNull(kiteSceneInst) ? kiteSceneInst.getProvinceNbr() : "";
        // 获取导入模版
        KiteBatchConfig kiteBatchConfig = localBatchAcceptService.queryConfigByOfferId(applyRegionCode, cateId, offerId, fileName);
        KiteAssert.notNull(kiteBatchConfig, ErrorConsts.BUSI_COMMON_ERROR, "查询模版配置失败，请确定模版是否配置");
        //        List<String> titleAttrs = KiteBeanUtils.copyPropsForList(dataList.get(2), String.class);
        List<List<String>> titleAttrs = new ArrayList<>();
        dataList.subList(0, 2).forEach(temp -> {
            List<String> titleAttr = JSONObject.parseArray(JSONObject.toJSONString(temp), String.class);
            titleAttrs.add(titleAttr);
        });
        List<Map<String, Object>> tmpAttrs = BatchAcceptUtil.packageTmpAttr(offerId, titleAttrs);
        System.out.println(JSONObject.toJSONString(tmpAttrs));
        // datas中的第一行是表头，校验列数是否跟模板一致、内容是否一致
        Integer columnNum = kiteBatchConfig.getTmplColumnNum();
        if (Objects.isNull(columnNum)) {
            columnNum = Objects.requireNonNull(JSONObject.parseArray(kiteBatchConfig.getTmplAttrJson())).size();
        }
        if (tmpAttrs.size() != columnNum || !KiteStringUtils
            .equals(JSONObject.toJSONString(tmpAttrs), kiteBatchConfig.getTmplAttrJson())) {
            BssException.throwOut("", "", "导入业务文件与当前受理商品规格不匹配，请重新选择");
        }
        return tmpAttrs;
    }

    @Override
    public void checkData(String sceneInstId, String batchId) {
        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("batchId", batchId);
        if (KiteStringUtils.isEmpty(batchId)) {
            BssException.throwOut("", "", "请先上传业务文件");
        }
        List<KiteBatchAcceptDetail> detailList = listDetial(paramMap);
        if (KiteListUtils.isEmpty(detailList)) {
            BssException.throwOut("", "", "请先上传业务文件");
        }
        KiteSceneInst kiteSceneInst = querySceneInstService.getSceneInst(sceneInstId);
        if (Objects.nonNull(kiteSceneInst) && KiteStringUtils
            .equalsAny(kiteSceneInst.getServiceOfferId(), LocalServiceOfferConsts.SERVICE_OFFER_COP_MEMBER_JOIN,
                LocalServiceOfferConsts.SERVICE_OFFER_COP_MEMBER_QUIT)) {
            return;
        }
        List<List<String>> dataList = querySceneInstService.getExtParameterValue(sceneInstId, "importDataList");
        if (KiteListUtils.isEmpty(dataList)) {
            return;
        }
        KiteOfferInst rootOfferInst = querySceneInstService.getOfferInst(kiteSceneInst.getCustId(), kiteSceneInst.getRootInstId());
        List<KiteProdInst> prodInstList = querySceneInstService
            .listProdInstsFromOfferInst(kiteSceneInst.getCustId(), kiteSceneInst.getRootInstId());
        // 目前只支持只有一个产品的
        KiteProdInst prodInst = prodInstList.get(0);
        List<KiteAttr> kiteAttrs = prodInst.listAttrs();
        Map<String, KiteAttr> kiteAttrMap = new HashMap<>();
        kiteAttrs.forEach(
            kiteAttr -> kiteAttrMap.put(kiteAttr.getCname(), KiteBeanUtils.transform(kiteAttr, KiteAttr.class)));
        // 切分Excel表头和实际数据
        int titileNum = BatchAcceptUtil.isTwoTitile(rootOfferInst.getAttrValue("cateId")) ? 2 : 1;
        List<String> titleList = BatchAcceptUtil.getTmpAttr(dataList.subList(0, titileNum), rootOfferInst.getAttrValue("cateId"));
        dataList = dataList.subList(titileNum, dataList.size());

        List<ContractOfferDetailDTO> offerDetailDTOList = querySceneInstService
            .getExtParameterValue(sceneInstId, "singleOffers");
        List<KiteAttrDTO> keyAttrs = Lists.newArrayList();
        if (KiteListUtils.isNotEmpty(offerDetailDTOList)) {
            offerDetailDTOList.forEach(detailDTO -> keyAttrs.addAll(detailDTO.getAttrs()));
        }

        KiteBatchAccept kiteBatchAccept = new KiteBatchAccept();
        kiteBatchAccept.setStatusCd(BatchAcceptStatusEnum.STATUS_CD_1200.getStatusCd());

        // 获取省名称（校验）
        List<UnicomRegion> provinces = SpringUtil.getBean(IUnicomRegionService.class).subRegionFromPlatform(new UnicomRegionQry());
        UnicomRegion province = Objects.requireNonNull(provinces).stream()
            .filter(unicomRegion -> KiteStringUtils.isEqual(unicomRegion.getRegionCode(), kiteSceneInst.getProvinceNbr())).findFirst()
            .orElse(new UnicomRegion());
        String provinceName = province.getRegionName();

        // 创建一个时间标示，作为当前线程池的标识；
        String taskId = String.valueOf(System.currentTimeMillis());
        // 获取多线程管理类
        MultiThreaExecutorManager mteMgr = MultiThreaExecutorManager.getInstans();
        ExecutorTypeEmun type = ExecutorTypeEmun.THREAD_POOL_TYPE_COMM_CACHE;
        String threadNumStr = DcSystemParamCache.getDcParamVal("BATCH_CHECK_DATA_THREAD_NUM");
        int threadNum = 5;
        if (KiteStringUtils.isNotBlank(threadNumStr) && KiteStringUtils.isNum(threadNumStr)) {
            threadNum = Integer.parseInt(threadNumStr);
        }

        mteMgr.newFixedThreadPool(type, taskId, threadNum);
        // 创建执行线程类集合
        Collection<ExecuteTask> executeTasks = new ArrayList<>();
        // 将这个集合放入管理器中的
        mteMgr.putTask(type, taskId, executeTasks);
        // 创建执行任务类
        for (int i = 0; i < dataList.size(); i++) {
            ExecuteTask task = new InputCheckDataTask(type, taskId, dataList.get(i), detailList.get(i), kiteAttrMap,
                titleList, prodInst, keyAttrs, provinceName);
            executeTasks.add(task);
        }
        try {
            long start = System.currentTimeMillis();
            // 启动多线程任务
            mteMgr.invokeAll(type, taskId);
            long end = System.currentTimeMillis();
            System.out.println("总消耗时间：" + (end - start) + "ms");
        }
        catch (Exception e) {
            kiteBatchAccept.setStatusDesc(e.getMessage());
            kiteBatchAccept.setStatusCd(BatchAcceptStatusEnum.STATUS_CD_1300.getStatusCd());
            System.out.println(e.getMessage());
        }
        finally {
            // 执行完后关闭线程
            mteMgr.shutDown(type, taskId);
            mteMgr.shutDownNow(type, taskId);
        }
        Example example = new Example(KiteBatchAccept.class);
        example.createCriteria().andEqualTo("batchId", batchId);
        kiteBatchAcceptMapper.updateByExampleSelective(kiteBatchAccept, example);
        for (KiteBatchAcceptDetail kiteBatchAcceptDetail : detailList) {
            Example detailExample = new Example(KiteBatchAcceptDetail.class);
            detailExample.createCriteria().andEqualTo("detailId", kiteBatchAcceptDetail.getDetailId())
                .andEqualTo("batchId", kiteBatchAcceptDetail.getBatchId());
            kiteBatchAcceptDetailMapper.updateByExampleSelective(
                new KiteBatchAcceptDetail().setCheckStatus(kiteBatchAcceptDetail.getCheckStatus())
                    .setCheckResult(kiteBatchAcceptDetail.getCheckResult()), detailExample);
        }
    }

    @Override
    public void deleteData(String batchId) {
        kiteBatchAcceptMapper.deleteByPrimaryKey(batchId);

        Example detailExample = new Example(KiteBatchAcceptDetail.class);
        detailExample.createCriteria().andEqualTo("batchId", batchId);
        kiteBatchAcceptDetailMapper.deleteByExample(detailExample);
    }

    @Override
    public String deleteDetailData(String sceneInstId, String custId, String batchId, String detailId) {
        KiteBatchAccept kiteBatchAccept = this.getKiteBatchAccept(batchId);
        kiteBatchAccept.setImportNum(kiteBatchAccept.getImportNum() - 1);
        this.kiteBatchAcceptMapper.updateByPrimaryKey(kiteBatchAccept);

        Example detailExample = new Example(KiteBatchAcceptDetail.class);
        detailExample.createCriteria().andEqualTo("batchId", batchId).andEqualTo("detailId", detailId);

        KiteBatchAcceptDetail detail = kiteBatchAcceptDetailMapper.selectOneByExample(detailExample);

        kiteBatchAcceptDetailMapper.deleteByExample(detailExample);
        return detail.getOfferInstId().toString();
    }

    @Override
    public boolean deleteOfferInstAndRelInsts(String sceneInstId, String custId, String offerInstId) {
        Assert.hasText(offerInstId, "offerInstId can not be empty");
        List<KiteProdInst> prodInsts = this.querySceneInstService.listProdInstsFromOfferInst(custId, offerInstId);
        if (!KiteListUtils.isEmpty(prodInsts)) {
            for (KiteProdInst prodInst : prodInsts) {
                operateSceneProdInstService.removeProdInst(sceneInstId, prodInst.getProdInstId());
            }
        }
        KiteOfferInst kiteOfferInst = this.querySceneInstService.getOfferInst(custId, offerInstId);
        if (!KiteObjectUtils.isEmpty(kiteOfferInst)) {
            this.querySceneInstService.listOfferInstContracts(custId, offerInstId).forEach(contract -> {
                this.operateSceneInstService.deleteOfferInstContract(sceneInstId, contract.getOfferObjInstRelId());
            });

            this.querySceneInstService.listOfferInstAccts(custId, offerInstId).forEach(acct -> {
                this.operateSceneInstService.deleteOfferInstAcct(sceneInstId, acct.getOfferObjInstRelId());
            });

            this.querySceneInstService.listOfferInstDiscounts(custId, offerInstId).forEach(discount -> {
                this.operateSceneInstService.deleteOfferInstDiscount(sceneInstId, discount.getOfferObjInstRelId());
            });

            this.operateSceneInstService.deleteAdditionalOfferInst(sceneInstId, offerInstId);

            String offerType = OfferCache.get(kiteOfferInst.getOfferId()).getOfferType();
            operateSceneOfferInstService.removeOffer(sceneInstId, custId, offerInstId, offerType);
        }
        return Boolean.TRUE;
    }

    @Override
    public List<KiteBatchAcceptDetail> listDetial(Map<String, Object> paramMap) {
        return kiteBatchAcceptDetailMapper.queryKiteBatchAcceptDetail(paramMap);
    }

    @Override
    public PageInfo<KiteBatchAcceptDetail> listDetialForPage(Map<String, Object> paramMap) {
        String pageNum = KiteMapUtils.getString(paramMap, "pageNum");
        String pageSize = KiteMapUtils.getString(paramMap, "pageSize");
        pageNum = !KiteStringUtils.isEmpty(pageNum) ? pageNum : "1";
        pageSize = !KiteStringUtils.isEmpty(pageSize) ? pageSize : "10";
        Integer intpageNum = Integer.parseInt(pageNum);
        Integer intPageSize = Integer.parseInt(pageSize);
        PageHelper.startPage(intpageNum, intPageSize);
        List<KiteBatchAcceptDetail> list = kiteBatchAcceptDetailMapper.queryKiteBatchAcceptDetail(paramMap);
        return new PageInfo<>(list);
    }

    @Override
    public List<KiteBatchAcceptDetail> listCheckFailDetail(String batchId) {
        Example example = new Example(KiteBatchAcceptDetail.class);
        example.createCriteria().andEqualTo("batchId", batchId).andEqualTo("checkStatus", "1100");
        return kiteBatchAcceptDetailMapper.selectByExample(example);
    }

    @Override
    public KiteBatchAccept getKiteBatchAccept(String batchId) {
        Example example = new Example(KiteBatchAccept.class);
        example.createCriteria().andEqualTo("batchId", batchId);
        return kiteBatchAcceptMapper.selectOneByExample(example);
        //return kiteBatchAcceptMapper.selectByPrimaryKey(Long.valueOf(batchId));
    }

    @Override
    public KiteBatchAcceptDetail getBatchAcceptDetail(String detailId, String batchId) {
        return kiteBatchAcceptDetailMapper.selectOne(
            new KiteBatchAcceptDetail().setDetailId(Long.valueOf(detailId)).setBatchId(Long.valueOf(batchId)));
    }

    @Override
    public List<BatchAccepImportFileVO> listImportFile(String sceneInstId, String offerInstId, String custId) {
        List<BatchAccepImportFileVO> importList = new ArrayList<>();
        AtomicInteger i = new AtomicInteger(1);
        // 业务文件导入
        String batchId = querySceneInstService.getExtParameterValue(sceneInstId, "batchId");
        if (KiteStringUtils.isNotBlank(batchId)) {
            KiteBatchAccept batchAccept = this.getKiteBatchAccept(batchId);
            if (Objects.nonNull(batchAccept)) {
                BatchAccepImportFileVO batchAccepImportFileVO = new BatchAccepImportFileVO();
                batchAccepImportFileVO.setId(String.valueOf(i.get())).setFileTypeName("业务文件")
                    .setFileType(LocalKeyConsts.BATCH_ACCEPT_INPUT_FILE_TYPE_1000).
                    setFileName(batchAccept.getFileName()).setStatusCd(batchAccept.getStatusCd())
                    .setStatusName(BatchAcceptStatusEnum.getStatusNameByCd(batchAccept.getStatusCd()))
                    .setUploadTime(KiteDateUtils.formatLocalDateTime(batchAccept.getCreateDate()));
                importList.add(batchAccepImportFileVO);
                i.getAndIncrement();
            }
        }
        // 合同设置
//        List<KiteOfferInstContract> contractList = querySceneInstService.listOfferInstContracts(custId, offerInstId);
//        if (KiteListUtils.isNotEmpty(contractList)) {
//            // 过滤掉动作为D的
//            contractList.removeIf(contract -> KiteStringUtils
//                .equalsAny(contract.getActionType().name(), ActionType.D.name(), ActionType.X.name()));
//            contractList.forEach(contract -> {
//                String fileName = KiteStringUtils.substring(contract.getContractUrl(),
//                    KiteStringUtils.lastIndexOf(contract.getContractUrl(), "*_*") + 3);
//                BatchAccepImportFileVO batchAccepImportFileVO = new BatchAccepImportFileVO();
//                batchAccepImportFileVO.setId(String.valueOf(i.get())).setFileTypeName("合同文件")
//                    .setFileType(LocalKeyConsts.BATCH_ACCEPT_INPUT_FILE_TYPE_2000).setFileName(fileName)
//                    .setStatusCd(BatchAcceptStatusEnum.STATUS_CD_1000.getStatusCd())
//                    .setStatusName(BatchAcceptStatusEnum.STATUS_CD_1000.getStatusName())
//                    .setUploadTime(KiteDateUtils.formatDate(contract.getCreateDate(), KiteDateUtils.DATE_TIME_FORMAT));
//                importList.add(batchAccepImportFileVO);
//                i.getAndIncrement();
//            });
//        }
//        // 折扣设置
//        LocalOperateOfferInstDiscountService operateOfferInstDiscountService = SpringUtil
//            .getBean(LocalOperateOfferInstDiscountService.class);
//        List<KiteOfferInstDiscount> discountList = operateOfferInstDiscountService
//            .listOfferInstDiscounts(sceneInstId, custId, offerInstId);
//        if (KiteListUtils.isNotEmpty(discountList)) {
//            discountList.removeIf(discount -> KiteStringUtils
//                .equalsAny(discount.getActionType().name(), ActionType.D.name(), ActionType.X.name()));
//            discountList.forEach(discount -> {
//                String fileName = KiteStringUtils.substring(discount.getDiscountFileUrl(),
//                    KiteStringUtils.lastIndexOf(discount.getDiscountFileUrl(), "*_*") + 3);
//                BatchAccepImportFileVO batchAccepImportFileVO = new BatchAccepImportFileVO();
//                batchAccepImportFileVO.setId(String.valueOf(i.get())).setFileTypeName("折扣文件")
//                    .setFileType(LocalKeyConsts.BATCH_ACCEPT_INPUT_FILE_TYPE_3000).setFileName(fileName)
//                    .setStatusCd(BatchAcceptStatusEnum.STATUS_CD_1000.getStatusCd())
//                    .setStatusName(BatchAcceptStatusEnum.STATUS_CD_1000.getStatusName())
//                    .setUploadTime(KiteDateUtils.formatDate(discount.getCreateDate(), KiteDateUtils.DATE_TIME_FORMAT));
//                importList.add(batchAccepImportFileVO);
//                i.getAndIncrement();
//            });
//        }
        return importList;
    }

    @Override
    public PageInfo<BusimportDetailVO> listImportDetails(String custId, String sceneInstId, String searchContent,
                                                         Integer pageNum, Integer pageSize) {
        List<BusimportDetailVO> importDetails = Lists.newArrayList();
        String batchId = this.querySceneInstService.getExtParameterValue(sceneInstId, "batchId");
        KiteBatchAccept kiteBatchAccept = this.getKiteBatchAccept(batchId);
        if (KiteObjectUtils.isEmpty(kiteBatchAccept)) {
            ErrorConsts.BUSI_COMMON_ERROR.throwOut("未获取到导入批次信息：" + batchId);
        }
        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("batchId", Long.valueOf(batchId));
        paramMap.put("attrJson", searchContent);
        paramMap.put("pageNum", pageNum);
        paramMap.put("pageSize", pageSize);
        paramMap.put("checkStatus", BatchAcceptStatusEnum.CHECK_STATUS_1200.getStatusCd());
        paramMap.put("statusCd", "1000");
        PageInfo<KiteBatchAcceptDetail> searchImportDetails = listDetialForPage(paramMap);
        searchImportDetails.getList().forEach(detail -> {
            BusimportDetailVO detailVO = new BusimportDetailVO();
            detailVO.setDetailId(detail.getDetailId().toString());
            detailVO.setOfferId(kiteBatchAccept.getOfferId());
            detailVO.setOfferName(kiteBatchAccept.getOfferName());
            List<KiteAttr> attrList = JSONObject.parseArray(detail.getAttrJson(), KiteAttr.class);

            // 替换成实例中的属性
            if (KiteListUtils.isNotEmpty(attrList) && Objects.nonNull(detail.getOfferInstId())) {
                String offerInstId = String.valueOf(detail.getOfferInstId());
                List<KiteProdInst> kiteProdInsts =
                    querySceneInstService.listProdInstsFromOfferInst(custId, offerInstId);
                KiteProdInst prodInst = kiteProdInsts.get(0);
                for (KiteAttr kiteAttr : attrList) {
                    KiteAttr instAttr = prodInst.getAttr(kiteAttr.getFieldName());
                    if (Objects.isNull(instAttr)) {
                        continue;
                    }
                    if (KiteStringUtils.equals("2_0000105", kiteAttr.getFieldName())) {
                        // mv
                        String valueDesc = instAttr.getValueDesc();
                        String[] valueArray = valueDesc.split(",");
                        kiteAttr.setValue(KiteStringUtils.concatArrayWithSymbol(valueArray, "/"));
                    } else {
                        kiteAttr.setValue(instAttr.getValueDesc());
                    }
                }
                BatchAcceptUtil.delInstAddress(prodInst, attrList,
                    "2_0000209", "2_0000211", "2_0000220");
                BatchAcceptUtil.delInstAddress(prodInst, attrList,
                    "2_0000105", "2_0000117", "2_0000107");
            }

            // A端省
            BatchAcceptUtil.delAddress(attrList, "2_0000220", "2_0000221", "2_0000222");
            // z端省
            BatchAcceptUtil.delAddress(attrList, "2_0000107", "2_0000109", "2_0000111");
            // mv
            BatchAcceptUtil.delAddressMvCity(attrList, "2_0000105", "2_0000107", "2_0000109", "2_0000111");

            detailVO.setAttrs(attrList);

            importDetails.add(detailVO);
        });
        PageInfo pageInfo = new PageInfo<>();
        KiteBeanUtils.copyProperties(searchImportDetails, pageInfo);
        pageInfo.setList(importDetails);
        return pageInfo;
        //this.getShowAttrs(sceneInstId, custId, adjustmentInfo);
    }

    @Override
    public void deleteImportFile(String sceneInstId, String fileType, String custId, String offerInstId) {
        switch (fileType) {
            case LocalKeyConsts.BATCH_ACCEPT_INPUT_FILE_TYPE_1000:
                String batchId = querySceneInstService.getExtParameterValue(sceneInstId, "batchId");
                operateSceneInstService.removeExtParameter(sceneInstId, "batchId");
                // 删除文件上传
                this.deleteData(batchId);
                break;
            case LocalKeyConsts.BATCH_ACCEPT_INPUT_FILE_TYPE_2000:
                // 删除合同
                List<KiteOfferInstContract> contracts = querySceneInstService
                    .listOfferInstContracts(custId, offerInstId);
                if (!KiteListUtils.isEmpty(contracts)) {
                    contracts.forEach(contract -> {
                        if (!KiteStringUtils.equals(contract.getActionType().name(), ActionType.X.name())
                            && !KiteStringUtils.equals(contract.getActionType().name(), ActionType.D.name())) {
                            operateSceneInstService
                                .deleteOfferInstContract(sceneInstId, contract.getOfferObjInstRelId());
                        }
                    });
                }
                break;
            case LocalKeyConsts.BATCH_ACCEPT_INPUT_FILE_TYPE_3000:
                // 删除折扣审批
                List<KiteOfferInstDiscount> discountList = querySceneInstService
                    .listOfferInstDiscounts(custId, offerInstId);
                discountList.forEach(discount -> {
                    if (!KiteStringUtils.equals(discount.getActionType().name(), ActionType.X.name())
                        && !KiteStringUtils.equals(discount.getActionType().name(), ActionType.D.name())) {
                        operateSceneInstService.deleteOfferInstDiscount(sceneInstId, discount.getOfferObjInstRelId());
                    }
                });
                break;
            default:
                break;
        }
    }
}
